package com.demo.server3.service;

import com.demo.dto.UserModifyDTO;
import com.demo.rpc.annotation.RPCTransactional;
import com.demo.server3.dao.UserDao;
import com.demo.server3.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by hunter
 *
 * @Description
 */
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 普通rpc测试
     */
    public String test() {
        return "from server2 : success";
    }

    /**
     * 分布式事务测试
     *
     * @param modifyDTO
     */
    @RPCTransactional
    public void updateUser(UserModifyDTO modifyDTO) {
        System.out.println(modifyDTO);

        User user = new User();
        user.setId(modifyDTO.getUserId());
        user.setName(modifyDTO.getName());

        userDao.save(user);

        // 模拟业务错误, 此时本地事务应该不会被提交, server1、server2报错不提交事务
        // throw new RuntimeException();

        // 模拟超时, 此时本地事务被回滚, server、server2连接超时
        /*try {
            Thread.sleep(15 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }
}